﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Twi.COMMON.Core;

namespace Twi.DataAccess.Common
{
    /*
    * Copyright: ©2010-2014 Twilight软件开发工作室【Tyingsoft 踏影软件】版权所有
    * Author: feitianxinhong
    * Create date: 2013-08-31
    * Website: http://www.tyingsoft.com
    * Description: 通用数据权限
    * 
    */
    public class TwiDataAuthority
    {
        /// <summary>
        /// 获取当前用户所属角色拥有的数据权限
        /// </summary>
        /// <returns>
        /// 有两列,格式如：
        /// FFIELDNAME           FFIELDVALUE
        /// --------------------------------------------
        /// Sys_Park.ParkCode	 0001
        /// Sys_Park.ParkCode	 0001001
        /// Sys_Park.ParkID	     2
        /// Sys_Park.ParkID	     4
        /// Sys_Dept.DeptCode	 0
        /// Sys_Dept.DeptCode	 001
        /// Sys_Dept.DeptID	     1
        /// Sys_Dept.DeptID	     2
        /// -------------------------------------------
        /// </returns>
        public static DataTable GetUserDataAuthority()
        {
            DataTable dt = new DataTable();

            //默认启用数据权限，TwiIgnoreRDA=1 表示停用
            string twiIgnoreRDA = TwiConfigHelper.GetAppSettingValue("TwiIgnoreRDA");
            if (!string.IsNullOrEmpty(twiIgnoreRDA) || twiIgnoreRDA == "1")
            {
                return dt;
            }

            //未登录，这里不做不控制，前面有会专门的会话机制验证
            else if (UserContext.CurrentUser == null)
            {                
                return dt;
            }

            //超级管理员，不控制数据权限
            else if (UserContext.IsSupperUser(UserContext.CurrentUser.FNAME))
            {
                return dt;
            }
            else if (UserContext.RoleDataAuthority == null)
            {
                return dt;
            }
            return UserContext.RoleDataAuthority;
        }

        /// <summary>
        /// 是否控制数据权限
        /// </summary>
        public static bool CheckIsOnRight()
        {
            DataTable dt = GetUserDataAuthority();
            return dt.Rows.Count == 0 ? false : true;
        }
    }
}
